 package com.solution.wx.order.controller;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.wxpay.sdk.WXPay;
import com.google.gson.Gson;
import com.solution.admin.auth.service.UserService;
import com.solution.admin.company.entity.SysPayConfigEntity;
import com.solution.admin.company.service.SysPayConfigService;
import com.solution.admin.customer.entity.CompanyEntity;
import com.solution.admin.customer.entity.CompanyExpressConfigEntity;
import com.solution.admin.customer.entity.CustomerEntity;
import com.solution.admin.customer.entity.DeliveryAddressEntity;
import com.solution.admin.customer.service.CompanyExpressConfigService;
import com.solution.admin.customer.service.CompanyService;
import com.solution.admin.customer.service.CustomerService;
import com.solution.admin.customer.service.DeliveryAddressService;
import com.solution.admin.order.constants.OrderConstants;
import com.solution.admin.order.entity.OrderDeliveredBillEntity;
import com.solution.admin.order.entity.OrderDetailEntity;
import com.solution.admin.order.entity.OrderEntity;
import com.solution.admin.order.entity.OrderInvoiceEntity;
import com.solution.admin.order.entity.OrderLogEntity;
import com.solution.admin.order.entity.OrderPayEntity;
import com.solution.admin.order.entity.OrderProductDeliveredEntity;
import com.solution.admin.order.service.OrderDeliveredBillService;
import com.solution.admin.order.service.OrderService;
import com.solution.admin.product.entity.ProductEntity;
import com.solution.admin.product.entity.ProductSpecEntity;
import com.solution.admin.product.service.ProductService;
import com.solution.admin.promotion.entity.PromotionProductEntity;
import com.solution.admin.settings.entity.KeyMapEntity;
import com.solution.admin.settings.service.KeyMapService;
import com.solution.common.constants.PublicStatus;
import com.solution.common.controller.BaseController;
import com.solution.common.page.PageBean;
import com.solution.common.page.PageParam;
import com.solution.common.swiftpass.MD5;
import com.solution.common.swiftpass.SignUtils;
import com.solution.common.swiftpass.SwiftpassConfig;
import com.solution.common.swiftpass.XmlUtils;
import com.solution.common.utils.string.StringUtil;
import com.solution.pc.promotion.PromotionCheckUtil;
import com.solution.pc.shoppingcart.entity.ShoppingCartEntity;
import com.solution.pc.shoppingcart.service.ShoppingCartService;
import com.solution.wx.core.util.WechatUtil;
import com.solution.wx.order.config.WxpayConfig;
import com.solution.wx.share.entity.ShareInfoEntity;
import com.solution.wx.share.service.ShareInfoService;

/**
 * PC订单信息web控制层
 * @author lilp
 * @date 2017-09-14 23:35:39
 */
@RequestMapping("/wx/order")
@Controller
public class WxOrderController extends BaseController {

	private Logger logger = LoggerFactory.getLogger(WxOrderController.class);

	@Autowired
	private OrderService orderService;
	
	@Autowired
	private ShoppingCartService shoppingCartService;
	
	@Autowired
	private DeliveryAddressService deliveryAddressService;
	
	@Autowired
	private PromotionCheckUtil promotionCheckUtil;
	
	@Autowired
	private SysPayConfigService sysPayConfigService;
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private KeyMapService keyMapService;
	
	@Autowired
	private OrderDeliveredBillService orderDeliveredBillService;
	
	@Autowired
	private CustomerService customerService;

	@Autowired
	private CompanyService companyService;
	
	@Autowired
	private ProductService productService;
	
	@Autowired
	private CompanyExpressConfigService companyExpressConfigService;
	
	@Autowired
	private ShareInfoService shareInfoService;
	
	/**
	 * 分页查询我的订单
	 * @param order 接收界面查询条件参数
	 * @param request 请求对象
	 * @return 返回对应的页面视图
	 * @author lilp
 	 * @date 2017-09-14 23:35:39
	 */
	@RequestMapping("/list")
	public String listOrderPage(HttpServletRequest request, HttpServletResponse response){
		// 隐藏的参数，用于微信端下拉查询更多（分页）订单信息
		Map<String, Object> hiddenParamMap = new HashMap<String, Object>();
		// 同步异步请求标志(异步请求，返回json数据通过response.getWirter().write 刷入页面)
		String requestType = request.getParameter("requestType");
		String pageNumStr = request.getParameter("pageNum");
		if(StringUtil.isEmpty(pageNumStr)){
			pageNumStr = "1";
		}
		int pageNum = Integer.parseInt(pageNumStr);
		int numPerPage = 3;
		PageParam pageParam = super.getPageParam(request);
		pageParam.setPageNum(pageNum);
		pageParam.setNumPerPage(numPerPage);
		// 订单状态
		String orderStatus = request.getParameter("orderStatus");
		// 待评价状态 
		String appraiseFlag = request.getParameter("appraiseFlag");
		// 付款状态 
		String payStatus = request.getParameter("payStatus");
		// 付款方式
		String payModel = request.getParameter("payModel");
		
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("orderStatus", orderStatus);
		paramMap.put("customerId", getCustomerId());
		paramMap.put("appraiseFlag", appraiseFlag);
		paramMap.put("payStatus", payStatus);
		paramMap.put("payModel", payModel);
		try {
			PageBean pageBean = orderService.listMyOrderPage(pageParam, paramMap);
			List<Object> orderList = pageBean.getRecordList();
			// 处理商品详情数据的转化
			if(orderList != null && orderList.size() > 0){
				for (Object object : orderList) {
					OrderEntity order = (OrderEntity)object;
					String productDetail = order.getProductDetail();
					if(StringUtil.isNotEmpty(productDetail)){
						// 将商品详情json串转化为 OrderDetailEntity 列表
						String productDetailJsonStr = "["+productDetail+"]";
						List<OrderDetailEntity> orderDetailList = JSONArray.parseArray(productDetailJsonStr, OrderDetailEntity.class);
						// 如果是部分发货，前台用户也可以进行签收
						if(orderDetailList != null && orderDetailList.size() > 0){
							for (OrderDetailEntity detail : orderDetailList) {
								if(detail.getSendNum() > 0){
									order.setShowSign("true");
								}
								try {
									List<ProductSpecEntity> productSpecList = JSONArray.parseArray(detail.getProductSpec(), ProductSpecEntity.class);
									detail.setProductSpecList(productSpecList);
                                } catch (Exception e) {
                                	logger.error(e.getMessage());
                                }
							}
						}
						order.setProductList(orderDetailList);
					}
				}
			}
			
			// 如果是异步，直接写response
			if("sync".equals(requestType)){
				try {
					response.getWriter().write(JSONObject.toJSON(pageBean).toString());
					response.getWriter().flush();
					response.getWriter().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			
			request.setAttribute("orderList", pageBean.getRecordList());
			request.setAttribute("pageBean", pageBean);
			request.setAttribute("orderStatus", orderStatus);
			request.setAttribute("appraiseFlag", appraiseFlag);
			
			hiddenParamMap.put("orderStatus",orderStatus);
			hiddenParamMap.put("appraiseFlag",appraiseFlag);
			hiddenParamMap.put("payStatus",payStatus);
			hiddenParamMap.put("payModel",payModel);
			request.setAttribute("hiddenParamMap", hiddenParamMap);
			
		} catch (Exception e) {
			handleException("分页查询微信订单信息失败", logger, e);
		}
		return "/wx/order/order_list";
	}
	
	
	/**
	 * 分页查询我的订单
	 * @param request 请求对象
	 * @return 返回对应的页面视图
	 * @author lilp
 	 * @date 2017-09-14 23:35:39
	 */
	@RequestMapping("/detail")
	public String toOrderDetail(HttpServletRequest request){
		// 订单编号
		String orderCode = request.getParameter("orderCode");
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("orderCode", orderCode);
		try {
			// 查询单条订单
			List<OrderEntity> orderList = orderService.listOrder(paramMap);
			if (orderList != null && orderList.size() > 0) {
				OrderEntity order = orderList.get(0);
				if (StringUtil.isNotEmpty(order.getProductDetail())) {
					List<OrderDetailEntity> productList = JSONArray.parseArray("[" + order.getProductDetail() + "]",OrderDetailEntity.class);
						if (productList != null && productList.size() > 0) {
							for (OrderDetailEntity product : productList) {
								// 累计商品总金额 如果有商品调价，则按调价后价格，否则按商品原价
								product.setProductItemMoney((product.getProductAdjustPrice() == null ? product.getProductPrice() : product.getProductAdjustPrice())
										.multiply(new BigDecimal(product.getBuyNum())));
								if(StringUtil.isNotEmpty(product.getProductSpec())){
									List<ProductSpecEntity>  productSpecList = JSONArray.parseArray(product.getProductSpec(),ProductSpecEntity.class);
									product.setProductSpecList(productSpecList);
								}
						}
					}
					request.setAttribute("productList", productList);
				}
				request.setAttribute("order", order);
				
				// 查询已发货的商品清单
				List<OrderDeliveredBillEntity> deliveredList = orderDeliveredBillService.listOrderDeliveredBill(paramMap);
				request.setAttribute("deliveredList", deliveredList);
			}
		} catch (Exception e) {
			handleException("查询我订单详情页面", logger, e);
		}
		return "/wx/order/order_detail";
	}
	
	
	/**
	 * 查询订单商品清单
	 * @param request 请求对象
	 * @return 返回对应的页面视图
	 * @author lilp
 	 * @date 2017-09-14 23:35:39
	 */
	@RequestMapping("/detailProductList")
	public String detailProductList(HttpServletRequest request){
		// 订单编号
		String orderCode = request.getParameter("orderCode");
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("orderCode", orderCode);
		try {
			// 查询单条订单
			List<OrderEntity> orderList = orderService.listOrder(paramMap);
			if (orderList != null && orderList.size() > 0) {
				OrderEntity order = orderList.get(0);
				if (StringUtil.isNotEmpty(order.getProductDetail())) {
					List<OrderDetailEntity> productList = JSONArray.parseArray("[" + order.getProductDetail() + "]",OrderDetailEntity.class);
						if (productList != null && productList.size() > 0) {
							for (OrderDetailEntity product : productList) {
								// 累计商品总金额 如果有商品调价，则按调价后价格，否则按商品原价
								product.setSubTotalItemMoney((product.getProductAdjustPrice() == null ? product.getProductPrice() : product.getProductAdjustPrice())
										.multiply(new BigDecimal(product.getBuyNum())));
								product.setProductItemMoney((product.getProductAdjustPrice() == null ? product.getProductPrice() : product.getProductAdjustPrice()));
								if(StringUtil.isNotEmpty(product.getProductSpec())){
									List<ProductSpecEntity>  productSpecList = JSONArray.parseArray(product.getProductSpec(),ProductSpecEntity.class);
									product.setProductSpecList(productSpecList);
								}
						}
					}
					request.setAttribute("productList", productList);
				}
				request.setAttribute("order", order);
			}
		} catch (Exception e) {
			handleException("查询我订单详情页面", logger, e);
		}
		return "/wx/order/order_product_list";
	}
	
	
	/**
	 * 提交订单
	 * @param request 请求对象
	 * @param orderEntity 订单信息实体
	 * @return
	 * @author lilp
 	 * @date 2017-09-14 23:35:39
	 */
	@RequestMapping("/commitOrder")
	@ResponseBody
	public Map<String, Object> commitOrder(HttpServletRequest request) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		int result = 0;
		Map<String, Object> param = new HashMap<String, Object>();
		// 配送地址
		param.put("deliveryAddressId", request.getParameter("deliveryId"));
		param.put("shoppingcartIds", request.getParameter("shoppingcartIds"));
		param.put("payModel", request.getParameter("payModel"));
		param.put("deliveryType", request.getParameter("deliveryType"));
		param.put("invoiceType", request.getParameter("invoiceType"));
		param.put("invoiceId", request.getParameter("invoiceId"));
		param.put("points", request.getParameter("points"));
		param.put("modifier", getCurrentUserCodeWithAnonymous(request));
		
		// 保存订单信息
		// 【1】、生成订单编码 及 订单基本信息
		OrderEntity order = new OrderEntity();
		String currentUserCode = getCurrentUserCodeWithAnonymous(request).toLowerCase();
		// 订单编号   1位下单渠道+时间戳后8位+用户登录名后4位
		String orderCode = OrderConstants.ORDER_CHANNEL.PC.getCode()
				+String.valueOf(System.currentTimeMillis()).substring(3)
				+currentUserCode.substring(currentUserCode.length()-4);
		order.setOrderCode(orderCode);
		
		// 根据当前用户code查询客户及公司基本信息
		CompanyEntity company = getCompany();
		CustomerEntity customer = getCustomer();
		order.setCustomerId(getCustomerId());
		order.setCustomerCompanyId(company.getId());
		order.setCustomerCompanyName(company.getCompanyName());
		order.setCustomerName(customer.getUserName());
		order.setCustomerMobile(customer.getMobile());

		
		// 【2】重新计算订单价格
		// 订单金额、实付金额、积分折扣（消费积分、抵扣金额）、优惠券折扣、活动（满减）折扣、运费、调价、商品调价
		// 查询购物车结算商品->计算商品金额->计算活动->计算积分折扣->计算优惠券折扣
		// 【2-1】查询购物车金额
		List<String> shoppingcartIds = new ArrayList<String>();
		String itemIds = request.getParameter("shoppingcartIds");
		if(StringUtil.isNotEmpty(itemIds)){
			for (String id : itemIds.split(",")) {
				shoppingcartIds.add(id);
			}
		}
		param.put("shoppingcartIds", shoppingcartIds);
		// 临时存放订单详情列表
		List<OrderDetailEntity> orderDetailList = new ArrayList<OrderDetailEntity>();
		// 查询购物车结算的商品，形成订单详情记录
		List<ShoppingCartEntity> cartList = shoppingCartService.listShoppingCart(param);
		
		
		
		// 【2-2】积分折扣金额,设置消费积分及积分抵扣金额
		String points = request.getParameter("points");
		// 积分换算比例 ,暂时设为
		BigDecimal pointsRatio = OrderConstants.POINT_TO_MONEY_EXCHANGE_RATIO;
		BigDecimal pointsMoney = new BigDecimal(points).multiply(pointsRatio);
		// 积分抵扣金额
		order.setPointsMoney(pointsMoney);
		order.setUserPoints(new BigDecimal(points));
				
		// 【2-3】优惠券折扣
		String couponMoney =request.getParameter("couponMoney");
		order.setCouponMoney(new BigDecimal(couponMoney));
		// 使用优惠券的id
		String couponIds = request.getParameter("couponIds");
		order.setCouponIds(couponIds);
		
		// 【2-4】活动折扣
		// 用于根据商品编码product_code批量查询是否有参加活动
		List<String> productCodeList = new ArrayList<String>();
		for (ShoppingCartEntity sce : cartList) {
			// 提取商品product_code 字段
			productCodeList.add(sce.getProductCode());
		}
		// 重新计算商品活动折扣
		promotionCheckUtil.checkPromotion(cartList, productCodeList, getCustomerId());
		// 循环取出活动的结果 
		// 满赠 ： 赠品列表  赠送积分列表  赠送优惠券列表
		// 满减： 满减少金额
		// 满折：折扣
		
		// 订单总体折扣金额
		BigDecimal totalDiscountMoney = new BigDecimal(0);
		// 订单总体满减金额
		BigDecimal totalReduceMoney = new BigDecimal(0);
		
		for (ShoppingCartEntity item : cartList) {
			List<PromotionProductEntity>  allPromotionList = new ArrayList<PromotionProductEntity>();
			// 单个商品购买金额
			BigDecimal cartItemMoney = item.getProductPrice().multiply(new BigDecimal(item.getBuyNum()));
			// 满减记录
			List<PromotionProductEntity>  reduceList = item.getReduceList();
			if(reduceList != null && reduceList.size() > 0){
				allPromotionList.addAll(reduceList);
				for (PromotionProductEntity reduce : reduceList) {
					totalReduceMoney = totalReduceMoney.add(reduce.getReduceMoney());
				}
			}
			// 满赠记录
			List<PromotionProductEntity>  giftList = item.getGiftList();
			if(giftList != null && giftList.size() > 0){
				allPromotionList.addAll(giftList);
			}
			// 满折记录
			List<PromotionProductEntity>  discountList = item.getDiscountList();
			if(discountList != null && discountList.size() > 0){
				allPromotionList.addAll(discountList);
				for (PromotionProductEntity discount : discountList) {
					// (1-(折扣数字/10)) * 购买金额
					totalDiscountMoney = totalDiscountMoney.add(
							(new BigDecimal(1).subtract(discount.getDiscount().divide(new BigDecimal(10)))).multiply(cartItemMoney));
				}
			}
			if(allPromotionList.size() > 0){
				item.setPromotionInfo(JSONArray.toJSONString(allPromotionList));
			}
		}
		
		
		
		// 订单折扣金额  = 满减金额 + 满折金额
		BigDecimal totalDiscount =  totalDiscountMoney.add(totalReduceMoney);
		order.setPromotionDiscountMoney(totalDiscount);
		// 总商品金额
		BigDecimal totalProductMoney = new BigDecimal(0);
		for (ShoppingCartEntity sce : cartList) {
			totalProductMoney = totalProductMoney.add(sce.getProductPrice().multiply(new BigDecimal(sce.getBuyNum())));
			OrderDetailEntity detail = new OrderDetailEntity();
			detail.setOrderCode(orderCode);
			detail.setProductId(sce.getProductId());
			detail.setProductCode(sce.getProductCode());
			detail.setProductName(sce.getProductName());
			// 商品规格
			detail.setProductSpec(sce.getProductSpec());
			detail.setProductPrice(sce.getProductPrice());
			// 参加活动的信息
			detail.setPromotionInfo(sce.getPromotionDesc());
			// 活动具体结果
			List<PromotionProductEntity> promotionResultList = new ArrayList<PromotionProductEntity>();
			// 满减+满赠+满折列表 => promotionResult
			if(sce.getReduceList() != null){
				promotionResultList.addAll(sce.getReduceList());
			}
			if(sce.getGiftList() != null){
				promotionResultList.addAll(sce.getGiftList());
			}
			if(sce.getDiscountList() != null){
				promotionResultList.addAll(sce.getDiscountList());
			}
			detail.setPromotionResult(JSONArray.toJSONString(promotionResultList));
			
			detail.setProductAdjustPrice(detail.getProductPrice());
			detail.setBuyNum(sce.getBuyNum());
			detail.setImagePath(sce.getImagePath());
			
			// 商品赠送积分系数
			detail.setProductPointRatio(sce.getProductPointRatio());
			// 客户系数
			detail.setCustomerPointRatio(getCompany().getCustomerFactor());
			// 商品最大折扣积分系数(在订单中暂时无用)
			detail.setExchangePointRatio(sce.getExchangePointRatio());
			// 商品模拟成本 
			detail.setProductSimulatePrice(sce.getProductSimulatePrice());
			
			orderDetailList.add(detail);
			
			// 提取商品product_code 字段
			productCodeList.add(sce.getProductCode());
		}
		// 商品类型（即：订单金额）
		order.setOrderMoney(totalProductMoney);
		// 订单中商品金额合计
		order.setTotalProductMoney(totalProductMoney);
		
		
		// 【2-5】运费 
		// 配送方式
		String deliveryType = request.getParameter("deliveryType");
		String deliveryFeePayType = request.getParameter("deliveryFeePayType");
		order.setDeliveryType(deliveryType);
		// 运费支付方式
		order.setDeliveryFeePayType(deliveryFeePayType);
		order.setDeliveryFeeMoney(new BigDecimal(0));
		
		// 后台重新计算运费,不能使用前台计算的运费
		String deliveryAddressId = request.getParameter("deliveryAddressId");
		BigDecimal orderDeliveryFee = calucateDelvieryFee(shoppingcartIds, deliveryAddressId, deliveryType, deliveryFeePayType);
		order.setDeliveryFeeMoney(orderDeliveryFee);
	
		// 【2-6】订单实付 (商品金额-积分抵扣-优惠券抵扣-活动抵扣-运费-订单调价)
		order.setAdjustOrderMoney(new BigDecimal(0));
		order.setAdjustProductMoney(new BigDecimal(0));
		BigDecimal realPayMoney = order.getOrderMoney().subtract(order.getCouponMoney())
				.subtract(order.getPointsMoney()).subtract(order.getPromotionDiscountMoney())
				.add(order.getDeliveryFeeMoney()).subtract(order.getAdjustOrderMoney());
		order.setRealPayMoney(realPayMoney);
		
		// 【3】订单类型、订单状态、调价标识、删除标记、创建人
		String payModel = request.getParameter("payModel");
		if(OrderConstants.ORDER_PAY_MODEL.PAY_NOW.getCode().equals(payModel)){
			// 立即付款，初始订单状态为待支付
			order.setOrderStatus(OrderConstants.ORDER_STATUS.WAIT_TO_PAY.getCode());
		}else if(OrderConstants.ORDER_PAY_MODEL.PAY_DELIVERY.getCode().equals(payModel)){
			// 货到付款，初始订单状态为待上传合同
			order.setOrderStatus(OrderConstants.ORDER_STATUS.WAIT_TO_UPLOAD_CONTRACT.getCode());
		}
		// 不需要调价
		order.setAdjustPriceFlag("1");
		order.setOrderType(OrderConstants.ORDER_CHANNEL.PC.getCode());
		order.setIsDelete(PublicStatus.IS_DELETE.NORMAL.getId());
		order.setCreater(getUserName());
		
		// 【4】支付模式、支付方式、运费支付方式、配送类型
		order.setPayModel(request.getParameter("payModel"));
		order.setPayType(request.getParameter("payType"));
		order.setDeliveryFeePayType(request.getParameter("deliveryFeePayType"));
		order.setDeliveryType(request.getParameter("deliveryType"));
		
		// 【5】收货人姓名、联系方式、省市区街道、详细地址
		DeliveryAddressEntity address = deliveryAddressService.getDeliveryAddressById(Long.parseLong(deliveryAddressId));
		order.setProvinceCode(address.getProvinceCode());
		order.setProvinceName(address.getProvinceName());
		order.setCityCode(address.getCityCode());
		order.setCityName(address.getCityName());
		order.setAreaCode(address.getAreaCode());
		order.setAreaName(address.getAreaName());
		order.setStreetCode(address.getStreetCode());
		order.setStreetName(address.getStreetName());
		order.setAddress(address.getAddress());
		order.setReceiverName(address.getReceiverName());
		order.setReceiverMobile(address.getMobile());
		
		
		
		// 【6】发票类型
		String invoiceType = request.getParameter("invoiceType");
		order.setInvoiceType(invoiceType);
		// 增值赋发票信息
		OrderInvoiceEntity invoice = new OrderInvoiceEntity();
		invoice.setOrderCode(orderCode);
		invoice.setCompnayName(request.getParameter("companyName"));
		invoice.setTaxNo(request.getParameter("taxNo"));
		invoice.setRegisteAddress(request.getParameter("registeAddress"));
		invoice.setRegistePhone(request.getParameter("registePhone"));
		invoice.setOpenBankName(request.getParameter("openBankName"));
		invoice.setBankAccount(request.getParameter("bankAccount"));

		// 【7】业务员代码、业务中姓名(需要实时)
		Map<String, Object> userMap = companyService.getSalesmanByCompanyId(getCompanyId());
		order.setSalesmanCode(userMap.containsKey("salesmanCode") ? userMap.get("salesmanCode").toString() : "--");
		// 获取业务员姓名
		order.setSalesmanName(userMap.containsKey("salesmanName") ? userMap.get("salesmanName").toString() : "--");
		order.setIntro(request.getParameter("intro"));
		order.setDeliveryIntro(request.getParameter("deliveryIntro"));
		// 订单基本信息
		param.put("orderInfo", order);
		// 要结算的商品
		param.put("orderDetailList", orderDetailList);
		// 发票
		param.put("invoice", invoice);
		
		try {
			//记录日志
			OrderLogEntity orderLog = new OrderLogEntity();
			orderLog.setOrderCode(order.getOrderCode());
			orderLog.setOperaterCode(getUserCode());
			orderLog.setOperaterName(getUserName());
			orderLog.setOpTime(new Date());
//			orderLog.setLogType(logType);
			orderLog.setLogContent("提交订单成功");
			orderLog.setCreater(getUserName());
			param.put("orderLogEntity", orderLog);
			
			
			//如果是商品分享的支付订单需要记录
			String shareId = request.getParameter("shareId");
			if (StringUtil.isNotNull(shareId)) {
				ShareInfoEntity shareInfo = shareInfoService.getShareInfoById(Long.parseLong(shareId));
				Map<String, Object> paramMap = new HashMap<String, Object>();
				paramMap.put("shareId", shareId);
				paramMap.put("orderCode", order.getOrderCode());
				paramMap.put("orderStatus", order.getOrderStatus());
				// 目前假设分享的商品只能立即购买
				ShoppingCartEntity cartItem = cartList.get(0);
				paramMap.put("shareProductId", cartItem.getProductId());
				paramMap.put("productName", cartItem.getProductName());
				paramMap.put("productCode", cartItem.getProductCode());
				paramMap.put("productCategoryName", shareInfo.getProductCategoryName());
				param.put("shareInfo", paramMap);
			}
			
			result = orderService.commitOrder(param);
			resultMap.put("orderCode", orderCode);
			resultMap.put("deliveryAddress", address.getProvinceName()+address.getCityName()+address.getAreaName()+address.getStreetName());
			resultMap.put("receiverName", address.getReceiverName());
			resultMap.put("receiverMobile", order.getReceiverMobile());
			resultMap.put("realPayMoney", order.getRealPayMoney());
			resultMap.put("payModel", order.getPayModel());
			resultMap.put("redirectAdjust", order.getAdjustPriceFlag());
			resultMap.put(PublicStatus.RESULT_CODE, result>0?"1":"0");
			resultMap.put(PublicStatus.RESULT_MSG, result>0?"操作成功":"操作失败");
			
			
		} catch (Exception e) {
			resultMap.put(PublicStatus.RESULT_CODE, "0");
			resultMap.put(PublicStatus.RESULT_MSG, "操作失败");
			handleException("提交订单失败", logger, e);
		}
		return resultMap;
	}
	
	

	/**
	 * 计算订单运费
	 * @param shoppingcartIds
	 * @return
	 */
	private BigDecimal calucateDelvieryFee(List<String> shoppingcartIds , String deliveryAddressId , String deliveryType, String deliveryFeePayType){
		// 运费
		BigDecimal lastDeliveryFee = new BigDecimal(0);
		// 重新计算订单运费
		// 查询结算商品的默认运费，sql直接计算出整个订单商品的默认普通运费多少 ，快递物流运费多少，其它运费多少
		Map<String, Object> dparam = new HashMap<String, Object>();
		dparam.put("shoppingcartIdsList", shoppingcartIds);
		ProductEntity deliveryFee = productService.listShoppingcartProductDelivery(dparam);

		// deliveryAddressId
		// deliveryType
		// deliveryFeePayType

		// 普通物流运费
		BigDecimal normalDeliveryFee = deliveryFee.getNormalDeliveryFee();
		// 快递物流运费
		BigDecimal expressDeliveryFee = deliveryFee.getExpressDeliveryFee();
		// 其它物流运费
		BigDecimal otherDeliveryFee = deliveryFee.getOtherDeliveryFee();
		
		// 获取公司减免地址信息
		dparam.clear();
		dparam.put("companyId", getCompany().getId());
		List<CompanyExpressConfigEntity> freeAddressList = companyExpressConfigService.listCompanyExpressConfig(dparam);
		String normalDeliveryAddressIds = "";
		String expressDeliveryAddressIds = "";
		if (freeAddressList != null && freeAddressList.size() > 0) {
			for (CompanyExpressConfigEntity config : freeAddressList) {
				if (config.getExpressType() == 1) {
					normalDeliveryAddressIds = config.getAddressIdsStr();
				} else if (config.getExpressType() == 2) {
					normalDeliveryAddressIds = "all";
				} else if (config.getExpressType() == 3) {
					expressDeliveryAddressIds = config.getAddressIdsStr();
				} else if (config.getExpressType() == 4) {
					expressDeliveryAddressIds = "all";
				}
			}
		}
		
		if("02".equals(deliveryFeePayType)){
			// 到付运费为0
			return new BigDecimal(0);
		}
		
		if("1".equals(deliveryType)){
			// 客户自提
			lastDeliveryFee = new BigDecimal(0);
		}else if("2".equals(deliveryType)){
			// 普通物流 
			if("all".equals(normalDeliveryAddressIds)){
				lastDeliveryFee = new BigDecimal(0);
			}else{
				if(isFee(deliveryAddressId, normalDeliveryAddressIds)){
					lastDeliveryFee = new BigDecimal(0);
				}else{
					lastDeliveryFee = normalDeliveryFee;
				}
			}
		}else if("3".equals(deliveryType)){
			// 快递物流 
			if("all".equals(expressDeliveryAddressIds)){
				lastDeliveryFee = new BigDecimal(0);
			}else{
				if(isFee(deliveryAddressId, expressDeliveryAddressIds)){
					lastDeliveryFee = new BigDecimal(0);
				}else{
					lastDeliveryFee = expressDeliveryFee;
				}
			}
		}else if("4".equals(deliveryType)){
			lastDeliveryFee = otherDeliveryFee;
		}
		return lastDeliveryFee;
	}
	
	/**
	 * 判断物流地址是否在免费地址列表中
	 * @param deliveryAddressId
	 * @param deliveryAddressIds
	 * @return
	 */
	private boolean isFee(String deliveryAddressId, String deliveryAddressIds){
		boolean flag = false;
		if(StringUtil.isNotEmpty(deliveryAddressIds)){
			String[] addressIdArr = deliveryAddressIds.split(",");
			for (String addressId : addressIdArr) {
				if(deliveryAddressId.equals(addressId)){
					flag = true;
					break;
				}
			}
		}else{
			flag = false;
		}
		return flag;
	}
	
	/**
	 * 订单提交成功，货到付款时跳转到提交成功页面
	 * @param request
	 * @return
	 */
	@RequestMapping("/commitSuccess")
	public String commitSuccess(HttpServletRequest request){
		String orderCode = request.getParameter("orderCode");
		String deliveryAddress = request.getParameter("deliveryAddress");
		String receiverName = request.getParameter("receiverName");
		String receiverMobile = request.getParameter("receiverMobile");
		String realPayMoney = request.getParameter("realPayMoney");
		
		request.setAttribute("orderCode", orderCode);
		request.setAttribute("deliveryAddress", deliveryAddress);
		request.setAttribute("receiverName", receiverName);
		request.setAttribute("receiverMobile", receiverMobile);
		request.setAttribute("realPayMoney", realPayMoney);
		return "wx/order/order_success";
	}
	
	/**
	 * 订单提交成功，跳转到调价提示页面
	 * @param request
	 * @return
	 */
	@RequestMapping("/toOrderAdjustPage")
	public String toOrderAdjustPage(HttpServletRequest request){
		String orderCode = request.getParameter("orderCode");
		String deliveryAddress = request.getParameter("deliveryAddress");
		String receiverName = request.getParameter("receiverName");
		String receiverMobile = request.getParameter("receiverMobile");
		String realPayMoney = request.getParameter("realPayMoney");
		
		request.setAttribute("orderCode", orderCode);
		request.setAttribute("deliveryAddress", deliveryAddress);
		request.setAttribute("receiverName", receiverName);
		request.setAttribute("receiverMobile", receiverMobile);
		request.setAttribute("realPayMoney", realPayMoney);
		return "wx/order/order_adjust";
	}
	
	
	/**
	 * 订单提交成功，跳转到支付页面
	 * @param request
	 * @return
	 */
	@RequestMapping("/toOrderPay")
	public String toPay(HttpServletRequest request){
		String orderCode = request.getParameter("orderCode");
		String deliveryAddress = request.getParameter("deliveryAddress");
		String receiverName = request.getParameter("receiverName");
		String receiverMobile = request.getParameter("receiverMobile");
		String realPayMoney = request.getParameter("realPayMoney");
		
		request.setAttribute("orderCode", orderCode);
		if(StringUtil.isEmpty(realPayMoney)){
			// 从我的订单页面跳转过来的没有收货信息和付款金额  
			// 查询订单
			OrderEntity order = orderService.getOrderByCode(orderCode);
			request.setAttribute("deliveryAddress", order.getProvinceName()+order.getCityName()+order.getAreaName()+order.getStreetName()+order.getStreetName());
			request.setAttribute("receiverName", order.getReceiverName());
			request.setAttribute("receiverMobile", order.getReceiverMobile());
			request.setAttribute("realPayMoney", order.getRealPayMoney());
		}else{
			// 提交订单后直接跳转的支付页面(相关信息可以带过来)
			request.setAttribute("deliveryAddress", deliveryAddress);
			request.setAttribute("receiverName", receiverName);
			request.setAttribute("receiverMobile", receiverMobile);
			request.setAttribute("realPayMoney", realPayMoney);
		}
		// 查询银行账号
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("status", 1);
		List<SysPayConfigEntity> payAccountList = sysPayConfigService.listSysPayConfig(param);
		//查询已上传的支付凭证
		param.put("orderCode", orderCode);
		param.put("isDelete", 0);
		request.setAttribute("payAccountList", payAccountList);
		// 查询微信调用接口信息
		String jsapi_ticket = WechatUtil.getJspiTicket();
		String url = request.getRequestURL().toString();
		String urlParam = request.getQueryString();
		if (StringUtil.isNotNull(urlParam)) {
			url = url + "?" + urlParam;
		}
		Map<String, String> sign = WechatUtil.sign(jsapi_ticket, url);
		request.setAttribute("appId", WechatUtil.APPID);
		request.setAttribute("timestamp", sign.get("timestamp"));
		request.setAttribute("nonceStr", sign.get("nonceStr"));
		request.setAttribute("signature", sign.get("signature"));
		
		try {
			// 支付信息
			WxpayConfig config = WxpayConfig.getInstance();
			// WXPay wxPay = new WXPay(config);
			
			// 查询订单信息进行支付
			OrderEntity order = orderService.getOrderByCode(orderCode);
			if (null == order) {
				request.setAttribute("errMessage", "该订单不是待支付订单");
				return "wx/wx_error";
			}
			CustomerEntity customer = customerService.getCustomerById(getCustomerId());
			
			//创建订单交易记录(防止调价后订单号重复)
			String currentUserCode = getCurrentUserCodeWithAnonymous(request).toLowerCase();
			String outTradeNo = "wx"+OrderConstants.ORDER_CHANNEL.PC.getCode()
					+String.valueOf(System.currentTimeMillis()).substring(3)
					+currentUserCode.substring(currentUserCode.length()-4);
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("orderCode", orderCode);
			paramMap.put("outTradeNo", outTradeNo);
			paramMap.put("creater", getUserName());
			int count = orderService.saveOrderTrade(paramMap);
			if (count != 1) {
				request.setAttribute("errMessage", "生成交易记录失败");
				return "wx/wx_error";
			}
			
			/**
			HashMap<String, String> data = new HashMap<String, String>();
			data.put("body", "景旭商城订单支付");
			// 关联订单号
			data.put("out_trade_no", outTradeNo);
			data.put("fee_type", "CNY");
			data.put("total_fee", String.valueOf(order.getRealPayMoney().multiply(new BigDecimal(100)).intValue()));
			data.put("spbill_create_ip", config.getSpbillCreateIp());
			data.put("notify_url", config.getNotifyUrl());
			data.put("trade_type", "JSAPI");
			data.put("product_id", order.getId().toString());
			data.put("openid", customer.getOpenId());
			Map<String, String> prePayMap = wxPay.unifiedOrder(data);
			if (prePayMap.get("return_code").equals("SUCCESS") && prePayMap.get("result_code").equals("SUCCESS")) {
				//组装前端支付参数
				Map<String, String> payMap = new HashMap<String, String>();
				payMap.put("appId", config.getAppID());
				payMap.put("timeStamp", String.valueOf(System.currentTimeMillis()/1000));
				payMap.put("nonceStr", data.get("nonce_str"));
				payMap.put("package", "prepay_id="+prePayMap.get("prepay_id"));
				payMap.put("signType", data.get("sign_type"));
				//签名(package为关键字,前台无法读取,只作为后端签名使用,前端使用prepayId重新组装)
				payMap.put("paySign", WXPayUtil.generateSignature(payMap, config.getKey(), WXPayConstants.SignType.MD5));
				payMap.put("prepayId", prePayMap.get("prepay_id"));
				request.setAttribute("payMap", payMap);
			} else {
				if (prePayMap.get("return_code").equals("SUCCESS")) {
					request.setAttribute("errMessage", prePayMap.get("err_code_des"));
				} else {
					request.setAttribute("errMessage", prePayMap.get("return_msg"));
				}
				return "wx/wx_error";
			}
			*/
			
			SortedMap<String, String> map = new TreeMap<String, String>();
			map.put("service", "pay.weixin.jspay");
			map.put("mch_id", SwiftpassConfig.getMchId());
			map.put("out_trade_no", outTradeNo);
			map.put("sub_openid", customer.getOpenId());
			//map.put("sub_openid", "oK2lB052c4Ms99KfYi0TKvXBMlRg");
			map.put("sub_appid", config.getAppID());
			map.put("total_fee", String.valueOf((order.getRealPayMoney().multiply(new BigDecimal(100)).intValue())));
			map.put("mch_create_ip", SwiftpassConfig.getMchCreateIp());
	        map.put("sign_type", "MD5");
	        map.put("is_raw", "1");
	        map.put("notify_url", SwiftpassConfig.getWxOfficeAccountPayNotifyUrl());
	        map.put("nonce_str", String.valueOf(new Date().getTime()));
	        map.put("body", "景旭分销在线订单");
	        // 操作员编号，这是我们放入原始订单号，方便在银行的商户后台对账查询
		    map.put("op_user_id", orderCode);
	        
	        Map<String, String> params = SignUtils.paraFilter(map);
	        StringBuilder buf = new StringBuilder((params.size() + 1) * 10);
	        SignUtils.buildPayParams(buf, params, false);
	        String preStr = buf.toString();
	        String paySign = MD5.sign(preStr, "&key=" + SwiftpassConfig.getKey(), "utf-8");
	        map.put("sign", paySign);

	        String reqUrl = SwiftpassConfig.getPayReqUrl();
	        logger.debug("reqUrl：" + reqUrl);

	        logger.debug("reqParams:" + XmlUtils.parseXML(map));
	        CloseableHttpResponse response = null;
	        CloseableHttpClient client = null;
	        String res = null;
	        Map<String, String> resultMap = null;
	        try {
	            HttpPost httpPost = new HttpPost(reqUrl);
	            StringEntity entityParams = new StringEntity(XmlUtils.parseXML(map), "utf-8");
	            httpPost.setEntity(entityParams);
	            httpPost.setHeader("Content-Type", "text/xml;utf-8");
	            client = HttpClients.createDefault();
	            response = client.execute(httpPost);
	            if (response != null && response.getEntity() != null) {
	                resultMap = XmlUtils.toMap(EntityUtils.toByteArray(response.getEntity()), "utf-8");
	                res = XmlUtils.toXml(resultMap);
	                logger.debug("请求结果：" + res);
	                if (!SignUtils.checkParam(resultMap, SwiftpassConfig.getKey())) {
	                    res = "验证签名不通过";
	                } else {
	                    if ("0".equals(resultMap.get("status")) && "0".equals(resultMap.get("result_code"))) {
	                        String pay_info = resultMap.get("pay_info");
	                        logger.debug("pay_info : " + pay_info);
	                        res = "ok";
	                    } 
	                }
	            } else {
	                res = "操作失败";
	            }
	        } catch (Exception e) {
	        	logger.error("操作失败，原因：",e);
	            res = "系统异常";
	        } finally {
	            if (response != null) {
	                response.close();
	            }
	            if (client != null) {
	                client.close();
	            }
	        }
	        Map<String,String> result = new HashMap<String,String>();
	        if("ok".equals(res)){
	            result = resultMap;
	        }else{
	            result.put("status", "500");
	            result.put("msg", res);
	        }
	        request.setAttribute("resultMap", parsePayInfo(resultMap.get("pay_info")));
		} catch (Exception e) {
			handleException("微信支付败", logger, e);
		}
		return "wx/order/order_pay";
	}
	
	
	/**
	 * 将支付接口返回的支付参数解析成Map
	 * @param payInfo
	 * @return
	 */
	private Map<String, String> parsePayInfo(String payInfo){
		Map<String, String> payInfoMap = new HashMap<String, String>();
		if(StringUtil.isNotEmpty(payInfo)){
			JSONObject payJson = JSONObject.parseObject(payInfo);
			payInfoMap.put("appId", payJson.getString("appId"));
			payInfoMap.put("timeStamp", payJson.getString("timeStamp"));
			payInfoMap.put("nonceStr", payJson.getString("nonceStr"));
			payInfoMap.put("packageStr", payJson.getString("package"));
			payInfoMap.put("paySign", payJson.getString("paySign"));
			payInfoMap.put("signType", payJson.getString("signType"));
		}
		return payInfoMap;
	}

	/**
	 * 对公账户支付
	 * @param request
	 * @return
	 * @author xkl
	 * @date 2017年11月21日 下午4:31:09
	 */
	@RequestMapping("/publicPay")
	public String publicPay(HttpServletRequest request) {
		String orderCode = request.getParameter("orderCode");
		Long sysConfigPayId = Long.parseLong(request.getParameter("accountId"));
		String imgPath = request.getParameter("imgPath");

		OrderEntity order = orderService.getOrderByCode(orderCode);
		SysPayConfigEntity payAccount = sysPayConfigService.getSysPayConfigById(sysConfigPayId);
		OrderPayEntity orderPay = new OrderPayEntity();
		orderPay.setOrderCode(orderCode);
		
		String currentUserCode = getUserCode();
		// 支付流水号   P+时间戳后8位+用户登录名后4位
		String payCode = "P"+String.valueOf(System.currentTimeMillis()).substring(3)
						+currentUserCode.substring(currentUserCode.length()-4);
		orderPay.setPayCode(payCode);
		orderPay.setPayTime(new Date());
		orderPay.setPayMoney(order.getRealPayMoney());
		orderPay.setPayType(OrderConstants.ORDER_PAY_TYPE.PUBLIC_BANK_PAY.getCode());
		orderPay.setFilePath(imgPath);
		orderPay.setAccountName(payAccount.getAccountName());
		orderPay.setBankAccount(payAccount.getBankAccount());
		orderPay.setBankName(payAccount.getBankName());
		orderPay.setOpenBank(payAccount.getBankChild());
		orderPay.setConfirmStatus(OrderConstants.ORDER_CONTRACT_STATUS.NOT_CONFIRM.getCode());
		orderPay.setCreater(getUserName());
		
		//修改订单状态
		order.setOrderStatus(OrderConstants.ORDER_STATUS.WAIT_TO_APPROVE.getCode());
		order.setOrderStatusName(OrderConstants.ORDER_STATUS.WAIT_TO_APPROVE.getName());
		order.setPayType(OrderConstants.ORDER_PAY_TYPE.PUBLIC_BANK_PAY.getCode());
		order.setPayTypeName(OrderConstants.ORDER_PAY_TYPE.PUBLIC_BANK_PAY.getName());
		order.setOrderTime(new Date());
		order.setModifier(getUserName());
		
		//记录日志
		OrderLogEntity orderLog = new OrderLogEntity();
		orderLog.setOrderCode(order.getOrderCode());
		orderLog.setOperaterCode(getUserCode());
		orderLog.setOperaterName(getUserName());
		orderLog.setOpTime(new Date());
//		orderLog.setLogType(logType);
		orderLog.setLogContent("支付订单成功");
		orderLog.setCreater(getUserName());
		
		orderService.commitOrderPay(order, orderPay, orderLog);
		
		request.setAttribute("order", order);
		return "wx/order/pay_result";
	}
	
	/**
	 * 对私人银行卡支付
	 * @param request
	 * @return
	 * @author xkl
	 * @date 2017年11月21日 下午4:31:09
	 */
	@RequestMapping("/privatePay")
	public String privatePay(HttpServletRequest request) {
		String orderCode = request.getParameter("orderCode");
		Long sysConfigPayId = Long.parseLong(request.getParameter("accountId"));
		String imgPath = request.getParameter("imgPath");

		OrderEntity order = orderService.getOrderByCode(orderCode);
		SysPayConfigEntity payAccount = sysPayConfigService.getSysPayConfigById(sysConfigPayId);
		OrderPayEntity orderPay = new OrderPayEntity();
		orderPay.setOrderCode(orderCode);
		String currentUserCode = getUserCode();
		// 支付流水号   P+时间戳后8位+用户登录名后4位
				String payCode = "P"+String.valueOf(System.currentTimeMillis()).substring(3)
								+currentUserCode.substring(currentUserCode.length()-4);
		orderPay.setPayCode(payCode);
		orderPay.setPayTime(new Date());
		orderPay.setPayMoney(order.getRealPayMoney());
		orderPay.setPayType(OrderConstants.ORDER_PAY_TYPE.PRIVATE_BANK_PAY.getCode());
		orderPay.setFilePath(imgPath);
		orderPay.setAccountName(payAccount.getAccountName());
		orderPay.setBankAccount(payAccount.getBankAccount());
		orderPay.setBankName(payAccount.getBankName());
		orderPay.setOpenBank(payAccount.getBankChild());
		orderPay.setConfirmStatus(OrderConstants.ORDER_CONTRACT_STATUS.NOT_CONFIRM.getCode());
		orderPay.setCreater(getUserName());
		
		//修改订单状态
		order.setPayType(OrderConstants.ORDER_PAY_TYPE.PRIVATE_BANK_PAY.getCode());
		order.setPayTypeName(OrderConstants.ORDER_PAY_TYPE.PRIVATE_BANK_PAY.getName());
		order.setOrderStatus(OrderConstants.ORDER_STATUS.WAIT_TO_APPROVE.getCode());
		order.setOrderStatusName(OrderConstants.ORDER_STATUS.WAIT_TO_APPROVE.getName());
		order.setOrderTime(new Date());
		order.setModifier(getUserName());
		
		//记录日志
		OrderLogEntity orderLog = new OrderLogEntity();
		orderLog.setOrderCode(order.getOrderCode());
		orderLog.setOperaterCode(getUserCode());
		orderLog.setOperaterName(getUserName());
		orderLog.setOpTime(new Date());
//		orderLog.setLogType(logType);
		orderLog.setLogContent("支付订单成功");
		orderLog.setCreater(getUserName());
		
		orderService.commitOrderPay(order, orderPay, orderLog);
		
		request.setAttribute("order", order);
		return "wx/order/pay_result";
	}
	
	
	/**
	 * 跳转订单取消页面
	 * @param request 请求对象
	 * @author lilp
 	 * @date 2017-09-14 23:35:39
	 */
	@RequestMapping("/toCancelOrder")
	public String toCancelOrder(HttpServletRequest request){
		// 订单号
		String orderCode = request.getParameter("orderCode");
		try {
			// 查询订单取消原因
			List<KeyMapEntity>  cancelReasonList = keyMapService.listKeyMap("orderCancelReason");
			request.setAttribute("cancelReasonList", cancelReasonList);
			request.setAttribute("orderCode", orderCode);
		} catch (Exception e) {
			handleException("跳转订单取消页面失败", logger, e);
		}
		return "/wx/order/order_cancel";
	}
	
	
	/**
	 * 取消订单
	 * @param request 请求对象
	 * @author lilp
 	 * @date 2017-09-14 23:35:39
	 */
	@RequestMapping("/cancelOrder")
	@ResponseBody
	public Map<String, Object> cancelOrder(HttpServletRequest request){
		Map<String, Object> resultMap = new HashMap<String, Object>();
		// 订单号
		String orderCode = request.getParameter("orderCode");
		try {
			Map<String, Object> param = new HashMap<String , Object>();
			param.put("orderCode", orderCode);
			param.put("orderStatus", OrderConstants.ORDER_STATUS.CANCELED.getCode());
			param.put("cancelTime", new Date());
			param.put("cancelReason", request.getParameter("cancelReason"));
			param.put("modifier", getUserName());
			int result = orderService.cancelOrder(param);
			resultMap.put("resultCode", result>0?"1":"0");
			resultMap.put("resultMsg", result>0?"操作成功":"操作失败");
		} catch (Exception e) {
			handleException("取消订单错误", logger, e);
			resultMap.put("code", "0");
			resultMap.put("resultMsg", "操作失败");
		}
		return resultMap;
	}
	
	
	/**
	 * 跳转上传合同页面
	 * @param request 请求对象
	 * @author lilp
 	 * @date 2017-09-14 23:35:39
	 */
	@RequestMapping("/toUploadOrderContract")
	public String toUploadContract(HttpServletRequest request){
		// 订单号
		String orderCode = request.getParameter("orderCode");
		try {
			
			OrderEntity order = orderService.getOrderByCode(orderCode);
			request.setAttribute("realPayMoney", order.getRealPayMoney());
			// 查询微信调用接口信息
			String jsapi_ticket = WechatUtil.getJspiTicket();
			String url = request.getRequestURL().toString();
			String urlParam = request.getQueryString();
			if (StringUtil.isNotNull(urlParam)) {
				url = url + "?" + urlParam;
			}
			Map<String, String> sign = WechatUtil.sign(jsapi_ticket, url);
			request.setAttribute("appId", WechatUtil.APPID);
			request.setAttribute("timestamp", sign.get("timestamp"));
			request.setAttribute("nonceStr", sign.get("nonceStr"));
			request.setAttribute("signature", sign.get("signature"));
			
			request.setAttribute("orderCode", orderCode);
		} catch (Exception e) {
			handleException("跳转上传合同页面", logger, e);
		}
		return "/wx/order/order_upload_contract";
	}
	
	/**
	 * 上传订单合同
	 * @param request 请求对象
	 * @author lilp
 	 * @date 2017-09-14 23:35:39
	 */
	@RequestMapping("/uploadOrderContract")
	@ResponseBody
	public Map<String, Object> uploadOrderContract(HttpServletRequest request){
		Map<String, Object> resultMap = new HashMap<String, Object>();
		// 订单号
		String orderCode = request.getParameter("orderCode");
		String contractImagePath = request.getParameter("contractImagePath");
		String intro = request.getParameter("intro");
		try {
			Map<String, Object> param = new HashMap<String , Object>();
			param.put("orderCode", orderCode);
			// 上传订单合同后，订单状态修改为待审核
			param.put("orderStatus", OrderConstants.ORDER_STATUS.WAIT_TO_APPROVE.getCode());
			param.put("contractImagePath", contractImagePath);
			param.put("uploadContractTime", new Date());
			param.put("intro", intro);
			param.put("creater", getUserName());
			param.put("modifier", getUserName());
			int result = orderService.uploadOrderContract(param);
			resultMap.put("resultCode", result>0?"1":"0");
			resultMap.put("resultMsg", result>0?"操作成功":"操作失败");
		} catch (Exception e) {
			handleException("取消订单错误", logger, e);
			resultMap.put("code", "0");
			resultMap.put("resultMsg", "操作失败");
		}
		return resultMap;
	}
	
	
	/**
	 * 跳转确认收货(签收)页面
	 * @param request 请求对象
	 * @author lilp
 	 * @date 2017-09-14 23:35:39
	 */
	@RequestMapping("/toConfirmSign")
	public String toConfirmSign(HttpServletRequest request){
		// 订单号
		String orderCode = request.getParameter("orderCode");
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("orderCode", orderCode);
		try {
			// 查询订单
			Map<Long, OrderDetailEntity>  productMap = new HashMap<Long, OrderDetailEntity>();
			OrderEntity order = null;
			List<OrderEntity> orderList = orderService.listOrder(paramMap);
			if (orderList != null && orderList.size() > 0) {
				order = orderList.get(0);
				if (StringUtil.isNotEmpty(order.getProductDetail())) {
					List<OrderDetailEntity> productList = JSONArray.parseArray(
							"[" + order.getProductDetail() + "]",OrderDetailEntity.class);
					order.setProductList(productList);
					for (OrderDetailEntity product : productList) {
						productMap.put(product.getId(), product);
					}
				}
			}
			request.setAttribute("order", order);
				
			// 查询已发货的商品清单
			List<OrderDeliveredBillEntity> deliveredList = orderDeliveredBillService.listOrderDetailDelivered(paramMap);
			if(deliveredList != null && deliveredList.size() > 0 ){
				for (OrderDeliveredBillEntity product : deliveredList) {
					product.setOrderStatus(order.getOrderStatus());
					if(StringUtil.isNotEmpty(product.getDeliveredProductDetails())){
						List<OrderProductDeliveredEntity>  productList = JSONArray.parseArray("["+product.getDeliveredProductDetails()+"]", OrderProductDeliveredEntity.class);
						List<OrderDetailEntity>  detailList = new ArrayList<OrderDetailEntity>();
						if(productList != null && productList.size() > 0){
							for (OrderProductDeliveredEntity delivredProduct : productList) {
								OrderDetailEntity  tmpDetail = productMap.get(delivredProduct.getDetailId());
								OrderDetailEntity detail = new OrderDetailEntity();
								BeanUtils.copyProperties(detail, tmpDetail);
								detail.setSendNum(delivredProduct.getDeliveredNum());
								
								if(StringUtil.isNotEmpty(detail.getProductSpec())){
									List<ProductSpecEntity> productSpecList = JSONArray.parseArray(detail.getProductSpec(), ProductSpecEntity.class);;
									detail.setProductSpecList(productSpecList);
								}
								
								detailList.add(detail);
							}
						}
						product.setDeliveredProductList(detailList);
					}
				}
			}
			// 签收页面按显示待签收的物流单，及详情
			request.setAttribute("deliveredList", deliveredList);
		} catch (Exception e) {
			handleException("跳转确认收货页面失败", logger, e);
		}
		return "/wx/order/order_confirm_sign";
	}
	
	/**
	 * 确认收货
	 * @param request 请求对象
	 * @author lilp
 	 * @date 2017-09-14 23:35:39
	 */
	@RequestMapping("/confirmSign")
	@ResponseBody
	public Map<String, Object> confrimSign(HttpServletRequest request){
		Map<String, Object> resultMap = new HashMap<String, Object>();
		// 订单号
		String orderCode = request.getParameter("orderCode");
		String deliveryCode = request.getParameter("deliveryCode");
		String deliveryBillId = request.getParameter("deliveryBillId");
		try {
			Map<String, Object> param = new HashMap<String , Object>();
			param.put("orderCode", orderCode);
			// 签收订单，检查是否发货完成，发货完成则修改订单状态 
			param.put("deliveryCode", deliveryCode);
			param.put("deliveryBillId", deliveryBillId);
			param.put("signTime", new Date());
			param.put("signStatus", OrderConstants.ORDER_SIGN_STATUS.SIGNED.getCode());
			param.put("signName", getUserName());
			param.put("modifier", getUserName());
			
			//记录日志
			OrderLogEntity orderLog = new OrderLogEntity();
			orderLog.setOrderCode(orderCode);
			orderLog.setOperaterCode(getUserCode());
			orderLog.setOperaterName(getUserName());
			orderLog.setOpTime(new Date());
//			orderLog.setLogType(logType);
			orderLog.setLogContent("订单已签收");
			orderLog.setCreater(getUserName());
			param.put("orderLogEntity", orderLog);
			
			// 签收部分发货单
			int result = orderService.signHalfOrder(param);
			OrderEntity order = orderService.getOrderByCode(orderCode);
			if (OrderConstants.ORDER_STATUS.FINISHED.getCode().equals(order.getOrderStatus())) {
				resultMap.put("isFinished", 1);
			} else {
				resultMap.put("isFinished", 0);
			}
			resultMap.put("resultCode", result>0?"1":"0");
			resultMap.put("resultMsg", result>0?"操作成功":"操作失败");
		} catch (Exception e) {
			handleException("取消订单错误", logger, e);
			resultMap.put("code", "0");
			resultMap.put("resultMsg", "操作失败");
		}
		return resultMap;
	}
	
	/**
	 * 跳转至微信调价页面
	 * @param request
	 * @return
	 * @author xkl
	 * @date 2017年12月29日 下午3:54:29
	 */
	@RequestMapping("/toAdjustOrderProductPrice")
	public String toAdjustOrderProductPrice(HttpServletRequest request) {
		// 订单编号 
		String orderCode = request.getParameter("orderCode");
		request.setAttribute("orderCode", orderCode);
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("orderCode", orderCode);
		try {
			// 查询单条订单
			List<OrderEntity> orderList = orderService.listOrder(paramMap);
			if(orderList !=null && orderList.size() > 0){
				// 商品原价总金额
				BigDecimal totalProductMoney = new BigDecimal(0);
				OrderEntity order = orderList.get(0);
				if(StringUtil.isNotEmpty(order.getProductDetail())){
					List<OrderDetailEntity> productList = JSONArray.parseArray("["+order.getProductDetail()+"]",OrderDetailEntity.class);
					// 单品调价总计
					BigDecimal totalDiffMoney = new BigDecimal(0);
					if(productList != null && productList.size() > 0 ){
						for (OrderDetailEntity product : productList) {
							// 累计商品总金额 如果有商品调价，则按调价后价格，否则按商品原价计算
							BigDecimal itemMoney = product.getProductAdjustPrice().multiply(new BigDecimal(product.getBuyNum()));
							product.setSubTotalItemMoney(itemMoney);
							totalProductMoney = totalProductMoney.add(itemMoney);
							totalDiffMoney = totalDiffMoney.add((product.getProductPrice().subtract(product.getProductAdjustPrice()).multiply(new BigDecimal(product.getBuyNum()))));
						}
						request.setAttribute("totalDiffMoney", totalDiffMoney);
					}
				}
				request.setAttribute("totalProductMoney", totalProductMoney);
				JSONObject orderJson = JSON.parseObject(JSON.toJSONString(order));
				JSONArray productDetail = JSON.parseArray("["+orderJson.get("productDetail")+"]");
				for (int i = 0; i < productDetail.size(); i++) {
					JSONArray specArray = JSON.parseArray(productDetail.getJSONObject(i).getString("productSpec"));
					productDetail.getJSONObject(i).put("productSpec", specArray);
				}
				orderJson.put("productDetail", productDetail);
				request.setAttribute("order", orderJson);
				System.out.println(JSON.toJSONString(orderJson));
			}
		} catch (Exception e) {
			handleException("跳转到微信订单调价页面", logger, e);
		}
		return "/wx/order/order_adjust_price";
	}
	
	/**
	 * 微信订单调价操作
	 * @param request
	 * @return
	 * @author xkl
	 * @date 2018年1月5日 下午5:47:07
	 */
	@RequestMapping("/adjustOrderPrice")
	@ResponseBody
	public Map<String, Object> adjustOrderPrice(HttpServletRequest request) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		int result = 0;
		Map<String, Object> param = new HashMap<String, Object>();
		String orderCode = request.getParameter("orderCode");
		String ids = request.getParameter("ids");
		// 每个商品调价值，以,号隔开的字符串  
		String produtAdjustPrice = request.getParameter("produtAdjustPrice");
		String produtPrice = request.getParameter("produtPrice");
		
		// 对应每个商品购物数量，以,号隔开的字符串
		String buyNums = request.getParameter("buyNums");
		String deliveryFeeMoney = request.getParameter("deliveryFeeMoney");
		String orderAdjustMoney = request.getParameter("orderAdjustMoney");
		
		param.put("orderCode", orderCode);
		param.put("ids", ids);
		param.put("produtAdjustPrice", produtAdjustPrice);
		param.put("produtPrice", produtPrice);
		param.put("buyNums", buyNums);
		param.put("deliveryFeeMoney", deliveryFeeMoney);
		param.put("orderAdjustMoney", orderAdjustMoney);
		
		try {
			result = orderService.adjustOrderPrice(param);
			resultMap.put(PublicStatus.RESULT_CODE, result>0?"1":"0");
			resultMap.put(PublicStatus.RESULT_MSG, result>0?"调价成功":"调价失败");
		} catch (Exception e) {
			handleException("订单调价操作失败", logger, e);
		}
		return resultMap;
	}
	
}
